//
//  ProjectSeletedController.m
//  XiaoMiao
//
//  Created by kinglian_iOS_000 on 2018/1/30.
//  Copyright © 2018年 smallyou. All rights reserved.
//

#import "ProjectSeletedController.h"
#import "ProjectSeletedCell.h"
#import "ProjectSeletedHeadView.h"
#import "ProjectSeletedModel.h"
#import "ProjectSeletedIndexPath.h"
#import "XMCameraAngleController.h"
#import "XMUploadPhotoModel.h"

typedef NS_ENUM(NSUInteger, ProjectSeletedVCType) {
    ProjectSeletedVCTypeOld,
    ProjectSeletedVCTypeNewList,
//    ProjectSeletedVCTypeNewCamera,
};

@interface ProjectSeletedController ()<UITableViewDelegate, UITableViewDataSource, ProjectSeletedHeadViewDelegate, ProjectSeletedCellDelegate>
/** <#Description#> */
@property (nonatomic, assign) ProjectSeletedVCType VCType;
/** 新用户模型 */
@property (nonatomic, strong) BaseInfoModel *baseInfoModel;
/** 老用户id */
@property (nonatomic, copy) NSString *partyId;
/** 老用户 */
@property (nonatomic, copy) NSString *realName;

@property (strong, nonatomic) UITableView *tableView;
/** <#属性#> */
@property (nonatomic, strong) NSMutableArray <ProjectSeletedModel *>*projectArrayM;
/** <#属性#> */
@property (nonatomic, strong) UIButton *nextButton;
/** <#属性#> */
@property (nonatomic, strong) ProjectSeletedIndexPath *seletedIndexPath;
@end

@implementation ProjectSeletedController

// 初始化新建用户
- (instancetype)initNewListWithBaseInfoModel:(BaseInfoModel *)baseInfoModel {
    if (self = [super init]) {
        self.VCType = ProjectSeletedVCTypeNewList;
        self.baseInfoModel = baseInfoModel;
    }
    return self;
}

//- (instancetype)initNewCamera {
//    if (self = [super init]) {
//        self.VCType = ProjectSeletedVCTypeNewCamera;
//    }
//    return self;
//}

- (instancetype)initOldWithPartyId:(NSString *)partyId realName:(NSString *)realName {
    if (self = [super init]) {
        self.VCType = ProjectSeletedVCTypeOld;
        self.partyId = partyId;
        self.realName = realName;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"项目选择";
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(@0);
        make.bottom.mas_equalTo(@44);
    }];
    
    [self request_getProjectSeletedListData];
}

- (void)setupNextButton {
    [self.view addSubview:self.nextButton];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(@44);
    }];
}

#pragma mark - Request
- (void)request_getProjectSeletedListData {
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:kLoadingMsg];
    
    [AppNetwork getWithUrl:kProjectSeletedListUrl refreshCache:NO params:nil success:^(id response) {
        progressHUD.hidden = YES;
        
        self.projectArrayM = [ProjectSeletedModel mj_objectArrayWithKeyValuesArray:response[@"cateViews"]];
        for (int i = 0; i < self.projectArrayM.count; i++) {
            self.projectArrayM[i].isOpen = i==0? YES: NO;
            for (int j = 0; j < self.projectArrayM[i].cateViews.count; j++) {
                if (j == 0) {
                    for (int k = 0; k < self.projectArrayM[i].cateViews[j].cateViews.count; k++) {
                        self.projectArrayM[i].cateViews[j].cateViews[k].isTagSeleted = k==0? YES: NO;
                    }
                }else {
                    for (int k = 0; k < self.projectArrayM[i].cateViews[j].cateViews.count; k++) {
                        self.projectArrayM[i].cateViews[j].cateViews[k].isTagSeleted = NO;
                    }
                }
            }
        }
        
        [self.tableView app_reloadData];
        
        [self setupNextButton];
        
    } fail:^(AppError *error) {
        progressHUD.hidden = YES;
        [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.projectArrayM.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.projectArrayM[section].isOpen) {
        return 0.f;
    }
    return self.projectArrayM[section].cateViews.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProjectSeletedCell *cell = [tableView dequeueReusableCellWithIdentifier:[ProjectSeletedCell cellId]];
    
    cell.projectSeletedModel = self.projectArrayM[indexPath.section].cateViews[indexPath.row];
    cell.delegate = self;
    
    return cell;
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.projectArrayM[indexPath.section].cateViews[indexPath.row].parentTableCellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return [ProjectSeletedHeadView viewHeight];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ProjectSeletedHeadView *headView = [ProjectSeletedHeadView app_viewFromXib];
    headView.frame = CGRectMake(0, 0, kScreenWidth, [ProjectSeletedHeadView viewHeight]);
    headView.delegate = self;
    headView.section = section;
    headView.projectSeletedModel = self.projectArrayM[section];
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.f;
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = kBgColor;
}

#pragma mark - ProjectSeletedCellDelegate
- (void)projectSeletedCell:(ProjectSeletedCell *)projectSeletedCell projectSeletedModel:(ProjectSeletedModel *)projectSeletedModel seletedCollectionCellItem:(NSInteger)seletedCollectionCellItem {
    
    NSInteger second = -1;
    
    for (ProjectSeletedModel *cellModel in self.projectArrayM) {
        for (int i = 0; i < cellModel.cateViews.count; i++) {
            ProjectSeletedModel *collectionModel = cellModel.cateViews[i];
            if (collectionModel == projectSeletedModel) {
                second = i;
                for (int i = 0; i < collectionModel.cateViews.count; i++) {
                    collectionModel.cateViews[i].isTagSeleted = i==seletedCollectionCellItem? YES: NO;
                }
                
            }else {
                for (ProjectSeletedModel *itemModel in collectionModel.cateViews) {
                    itemModel.isTagSeleted = NO;
                }
            }
        } 
    }
    
    [self.tableView reloadData];
    
    if (second == -1) {
        [KLProgressHUD showPromptHUDWithMessage:@"程序忙，请稍后再试"];
        return;
    }
    
    self.seletedIndexPath.second = second;
    self.seletedIndexPath.third = seletedCollectionCellItem;
}

#pragma mark - ProjectSeletedHeadViewDelegate
// 点击箭头
- (void)projectSeletedHeadView:(ProjectSeletedHeadView *)projectSeletedHeadView openSection:(NSInteger)openSection {
    if (openSection > self.projectArrayM.count) {
        return;
    }
    
    for (int i = 0; i < self.projectArrayM.count; i++) {
        if (i == openSection) {
            self.projectArrayM[i].isOpen = YES;
            
            for (int j = 0; j < self.projectArrayM[i].cateViews.count; j++) {
                if (j == 0) {
                    for (int k = 0; k < self.projectArrayM[i].cateViews[j].cateViews.count; k++) {
                        self.projectArrayM[i].cateViews[j].cateViews[k].isTagSeleted = k==0? YES: NO;
                    }
                }else {
                    for (int k = 0; k < self.projectArrayM[i].cateViews[j].cateViews.count; k++) {
                        self.projectArrayM[i].cateViews[j].cateViews[k].isTagSeleted = NO;
                    }
                }
            }
            
        }else {
            self.projectArrayM[i].isOpen = NO;
            for (ProjectSeletedModel *model in self.projectArrayM[i].cateViews) {
                for (ProjectSeletedModel *subModel in model.cateViews) {
                    subModel.isTagSeleted = NO;
                }
            }
        }
    }
    
    [self.seletedIndexPath setFirst:openSection second:0 third:0];
    
    [self.tableView reloadData];
}

#pragma mark - Action
- (void)nextButtonDidClick {

    ProjectSeletedModel *firstModel = self.projectArrayM[self.seletedIndexPath.first]; //eg 整型的id
    ProjectSeletedModel *secondModel = firstModel.cateViews[self.seletedIndexPath.second]; //eg 隆鼻的id
    ProjectSeletedModel *thirdModel = secondModel.cateViews[self.seletedIndexPath.third];  //eg 术后的id
    
    //创建待上传拍照模型 -- 初始化分类
    XMUploadPhotoModel *uploadModel = nil;
    switch (self.VCType) {
        case ProjectSeletedVCTypeOld: {
            BaseInfoModel *model = [[BaseInfoModel alloc] init];
            model.realName = self.realName;
            uploadModel = [XMUploadPhotoModel uploadModelWithCateId:firstModel.id
                                                          subCateId:secondModel.id
                                                       subSubCateId:thirdModel.id
                                                                pId:self.partyId
                                                      baseInfoModel:model];
        }
            break;
            
        case ProjectSeletedVCTypeNewList: {
            uploadModel = [XMUploadPhotoModel uploadModelWithCateId:firstModel.id
                                                          subCateId:secondModel.id
                                                       subSubCateId:thirdModel.id
                                                      baseInfoModel:self.baseInfoModel];
        }
            break;
            
//        case ProjectSeletedVCTypeNewCamera:
//            uploadModel = [XMUploadPhotoModel uploadModelWithCateId:firstModel.id
//                                                          subCateId:secondModel.id
//                                                       subSubCateId:thirdModel.id
//                                                      baseInfoModel:nil];
//            break;
    }


    //选择拍照角度
    XMCameraAngleController *camera = [[XMCameraAngleController alloc] init];
    camera.uploadModel = uploadModel;
//    camera.isNewCamera = self.VCType == ProjectSeletedVCTypeNewCamera;
    [self.navigationController pushViewController:camera animated:YES];
}

#pragma mark - Lazy
- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 44 + 44, 0);
        tableView.backgroundColor = kBgColor;
        
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ProjectSeletedCell class]) bundle:nil] forCellReuseIdentifier:[ProjectSeletedCell cellId]];
        
        _tableView = tableView;
    }
    return _tableView;
}

- (UIButton *)nextButton {
    if (!_nextButton) {
        _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextButton.titleLabel setTextColor:[UIColor whiteColor]];
        [_nextButton.titleLabel setFont:[UIFont systemFontOfSize:16.f]];
        [_nextButton setBackgroundImage:[UIImage imageNamed:@"ic_common_bg_main"] forState:UIControlStateNormal];
        
        [_nextButton addTarget:self action:@selector(nextButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextButton;
}

- (ProjectSeletedIndexPath *)seletedIndexPath {
    if (!_seletedIndexPath) {
        _seletedIndexPath = [ProjectSeletedIndexPath indexPath];
    }
    return _seletedIndexPath;
}
@end
